package cn.jasonone.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jasonone.bean.SysResource;
import cn.jasonone.bean.SysUser;
import cn.jasonone.mapper.SysUserMapper;
import cn.jasonone.service.SysRoleService;
import cn.jasonone.service.SysUserService;

@Service
public class SysUserServiceImpl implements SysUserService {
	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private SysRoleService roleService;
	@Value("${roleAdmin:ADMINISTRATOR}")
	private String roleAdmin;

	@Transactional
	@Override
	public boolean save(SysUser user, int... roleIds) {
		sysUserMapper.save(user);
		if (roleIds.length > 0) {
			roleService.bindUser(user.getId(), roleIds);
		}
		return true;
	}

	@Override
	public boolean deleteByIds(int id) {
		return sysUserMapper.deleteByIds(id) > 0;
	}

	@Override
	public List<SysUser> findAll(SysUser user) {
		return sysUserMapper.findAll(user);
	}

	@Override
	public SysUser findById(int id) {
		return sysUserMapper.findById(id);
	}

	@Override
	public SysUser login(SysUser user) {
		SysUser login = sysUserMapper.login(user);
		if(login != null) {
			for (SysResource sysResource : login.getResources()) {
				if(sysResource.getPid() == -1) {
					sysResource.setChilds(tree(login.getResources(),sysResource.getId()));
				}
			}
		}
		return login;
	}
	
	public List<SysResource> tree(List<SysResource> resoruces,int id) {
		List<SysResource> childs=new ArrayList<>();
		if(resoruces != null) {
			for (SysResource sysResource : resoruces) {
				if(sysResource.getPid()==id) {
					childs.add(sysResource);
					sysResource.setChilds(tree(resoruces,sysResource.getId()));
				}
			}
		}
		return childs;
	}
	
	

}
